/**
 * 
 */
package scriptrunner.execution;

import java.io.Serializable;

/**
 * @author Administrator
 * 
 */
public class CpLessExpr extends CompareExpr implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7074018886879454699L;

	public CpLessExpr(EvaluateExpr eeLeft, EvaluateExpr eeRight) {
		this.eeLeft = eeLeft;
		this.eeRight = eeRight;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * scriptrunner.execution.CompareExpr#CalcluateResult(scriptrunner.execution
	 * .Session)
	 */
	@Override
	public boolean CalculateResult(Session se) throws ExecuteErrorException {
		ValueObject left = eeLeft.CalculateResult(se);
		ValueObject right = eeRight.CalculateResult(se);

		if (left instanceof ComparableValue && right instanceof ComparableValue) {
			// Same Class
			if (left.getClass() == right.getClass()) {
				return ((ComparableValue) left).LessThan((ComparableValue) right);
			} else {
				Class<?> matchedClass = CalculateClassMatch.CompareMatch(left,
						right);
				// Left and right are not comparable.
				if (matchedClass == null)
					throw new ExecuteErrorException("The two values cannot be compared by '<'");

				// Left
				ComparableValue nLeft;
				if (left.getClass() != matchedClass) {
					try {
						nLeft = (ComparableValue) matchedClass.newInstance();
						nLeft.ParseFromString(((ComparableValue) left)
								.SaveValueToString());
					} catch (Throwable o) {
						throw new ExecuteErrorException("The two values cannot be compared by '<'");
					}
				} else
					nLeft = (ComparableValue) left;

				// Right
				ComparableValue nRight;
				if (right.getClass() != matchedClass) {
					try {
						nRight = (ComparableValue) matchedClass.newInstance();
						nRight.ParseFromString(((ComparableValue) right)
								.SaveValueToString());
					} catch (Throwable o) {
						throw new ExecuteErrorException("The two values cannot be compared by '<'");
					}
				} else
					nRight = (ComparableValue) right;

				return nLeft.LessThan(nRight);
			}
		} else {
			throw new ExecuteErrorException("The two values cannot be compared by '<'");
		}
	}

	protected EvaluateExpr eeLeft, eeRight;
}
